const mongoose = require('mongoose');
const { Admin, RecipeCategory, Food, FoodCategory, Recipe } = require('../src/models');
const config = require('../src/config/config');

// 连接数据库
mongoose.connect(config.mongoose.url, config.mongoose.options).then(() => {
  console.log('Connected to MongoDB');
  initializeData();
}).catch((error) => {
  console.error('Error connecting to MongoDB:', error);
  process.exit(1);
});

async function initializeData() {
  try {
    // 清空现有数据
    await Promise.all([
      Admin.deleteMany({}),
      RecipeCategory.deleteMany({}),
      Food.deleteMany({}),
      FoodCategory.deleteMany({})
    ]);

    // 创建管理员用户
    const admin = await Admin.create({
      name: 'Admin',
      username: 'admin',
      password: 'admin123',
      email: 'admin@example.com',
      role: '超级管理员',
      isActive: true
    });

    // 创建食物分类
    const foodCategoriesData = [
      { name: "谷物", icon: "🍚", description: "提供主要碳水化合物", order: 1, isActive: true },
      { name: "蔬菜", icon: "🥦", description: "富含维生素和纤维", order: 2, isActive: true },
      { name: "水果", icon: "🍎", description: "天然糖分和维生素来源", order: 3, isActive: true },
      { name: "肉类", icon: "🥩", description: "主要蛋白质来源", order: 4, isActive: true },
      { name: "鱼类海鲜", icon: "🐟", description: "优质蛋白和不饱和脂肪酸", order: 5, isActive: true },
      { name: "蛋奶制品", icon: "🥛", description: "钙和蛋白质来源", order: 6, isActive: true },
      { name: "豆类坚果", icon: "🥜", description: "植物蛋白和健康脂肪", order: 7, isActive: true },
      { name: "油脂", icon: "🧈", description: "提供脂肪和能量", order: 8, isActive: true },
      { name: "饮品", icon: "🥤", description: "补充水分或其他", order: 9, isActive: true },
      { name: "零食", icon: "🍫", description: "休闲食品", order: 10, isActive: true },
      { name: "调味品", icon: "🧂", description: "增加风味", order: 11, isActive: true }
    ];

    const foodCategories = await FoodCategory.insertMany(foodCategoriesData);
    console.log(`${foodCategories.length} food categories inserted.`);

    // 创建一些基础食材
    const foodsData = [
      { 
        name: "米饭", 
        categoryId: foodCategories[0]._id,
        unit: "克", 
        calories: 130,
        nutrition: {
          protein: 2.7,
          fat: 0.3,
          carbohydrate: 28.2,
          fiber: 0.4,
          sugar: 0.1,
          sodium: 1,
          cholesterol: 0
        },
        isVerified: true,
        source: "USDA"
      },
      { 
        name: "西兰花", 
        categoryId: foodCategories[1]._id,
        unit: "克", 
        calories: 34,
        nutrition: {
          protein: 2.8,
          fat: 0.4,
          carbohydrate: 6,
          fiber: 2.6,
          sugar: 1.5,
          sodium: 33,
          cholesterol: 0
        },
        isVerified: true,
        source: "USDA"
      },
      { 
        name: "鸡胸肉", 
        categoryId: foodCategories[3]._id,
        unit: "克", 
        calories: 165,
        nutrition: {
          protein: 31,
          fat: 3.6,
          carbohydrate: 0,
          fiber: 0,
          sugar: 0,
          sodium: 74,
          cholesterol: 85
        },
        isVerified: true,
        source: "USDA"
      }
    ];

    const foods = await Food.insertMany(foodsData);
    console.log(`${foods.length} foods inserted.`);

    // 创建食谱分类
    const recipeCategoriesData = [
      { name: "家常菜", icon: "🍳", description: "日常简单菜肴", order: 1, isActive: true },
      { name: "快手菜", icon: "⏱️", description: "制作时间短", order: 2, isActive: true },
      { name: "烘焙", icon: "🍞", description: "面包、蛋糕等", order: 3, isActive: true },
      { name: "汤羹", icon: "🥣", description: "各类汤品", order: 4, isActive: true },
      { name: "饮品", icon: "🍹", description: "自制饮品", order: 5, isActive: true },
      { name: "西餐", icon: "🍝", description: "西式料理", order: 6, isActive: true },
      { name: "日韩料理", icon: "🍣", description: "日式和韩式菜肴", order: 7, isActive: true },
      { name: "健身餐", icon: "💪", description: "高蛋白低脂", order: 8, isActive: true },
      { name: "宝宝辅食", icon: "👶", description: "适合婴幼儿", order: 9, isActive: true },
      { name: "节日美食", icon: "🎉", description: "特殊场合菜肴", order: 10, isActive: true }
    ];

    const categories = await RecipeCategory.insertMany(recipeCategoriesData);
    console.log(`${categories.length} recipe categories inserted.`);

    // 创建示例食谱
    const recipesData = categories.map((category, index) => {
      // 随机选择1-3个食材
      const selectedFoods = [];
      const numIngredients = Math.floor(Math.random() * 3) + 1;
      for (let i = 0; i < numIngredients; i++) {
        const food = foods[Math.floor(Math.random() * foods.length)];
        selectedFoods.push({
          food: {
            _id: food._id,
            name: food.name
          },
          amount: Math.round(100 + Math.random() * 100),
          unit: food.unit
        });
      }

      // 计算食谱的总营养成分
      const totalNutrition = {
        calories: 0,
        protein: 0,
        fat: 0,
        carbohydrates: 0
      };

      selectedFoods.forEach(ingredient => {
        const food = foods.find(f => f._id.toString() === ingredient.food._id.toString());
        const ratio = ingredient.amount / 100; // 因为营养成分是按每100g计算的
        totalNutrition.calories += food.calories * ratio;
        totalNutrition.protein += food.nutrition.protein * ratio;
        totalNutrition.fat += food.nutrition.fat * ratio;
        totalNutrition.carbohydrates += food.nutrition.carbohydrate * ratio;
      });

      // 生成3-5个步骤
      const numSteps = Math.floor(Math.random() * 3) + 3;
      const steps = [];
      for (let i = 1; i <= numSteps; i++) {
        steps.push({
          stepNumber: i,
          description: `第${i}步：这是${category.name}示例食谱的第${i}个步骤。`,
          image: `https://example.com/images/step${i}.jpg`
        });
      }

      return {
        title: `示例食谱 ${index + 1}`,
        description: `这是一道美味的${category.name}示例食谱，简单易学。`,
        coverImage: `https://example.com/images/recipe${index + 1}.jpg`,
        category: {
          _id: category._id,
          name: category.name
        },
        difficulty: Math.floor(Math.random() * 5) + 1,
        prepTime: 10 + Math.floor(Math.random() * 20),
        cookTime: 15 + Math.floor(Math.random() * 45),
        servings: Math.floor(Math.random() * 4) + 1,
        ingredients: selectedFoods,
        steps: steps,
        nutrition: {
          calories: Math.round(totalNutrition.calories),
          protein: Math.round(totalNutrition.protein * 10) / 10,
          fat: Math.round(totalNutrition.fat * 10) / 10,
          carbohydrates: Math.round(totalNutrition.carbohydrates * 10) / 10
        },
        author: {
          _id: admin._id,
          name: admin.name,
          username: admin.username
        },
        isVerified: true
      };
    });

    const recipes = await Recipe.insertMany(recipesData);
    console.log(`${recipes.length} recipes inserted.`);

    console.log('Database initialization completed successfully.');
    process.exit(0);
  } catch (error) {
    console.error('Error initializing database:', error);
    process.exit(1);
  }
} 